/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: ParameterDummy.cpp,v 1.2 2009-11-09 08:57:33 morsko Exp $
 *
 * \file
 * \brief Example implementation for Parameter server module.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 ******************************************************************************
 * NOTE: The following 'Module Info' should be kept up-to-date. Do NOT
 * change its format, insert your information according to the template.
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 * - none
 *
 * Provides Interfaces:
 * - Parameter
 *
 * Needs Interfaces:
 * - none
 *
 * General information:
 * - This is a Dummy module for interface example purposes.
 * 
 ******************************************************************************
 */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "ParameterServer.hpp"

//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to ODINFO
static int verbose = ODINFO;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::Parameter;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup;
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************
TParameterInfoArray parameterArray;
int brightnessValue = 33;
int contrastValue = 43;
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(ODSTATUS,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(ODSTATUS,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tSQLSQL [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-f conf_file]\t\tUse 'conf_file' as configuration file for this module\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*************************************************************************
static void DummyExecuteParameterQuery(CParameterServer *ps, CParameterData &parameterdata, 
                                 const SMessageSource &ms, const TCommand *cmd)
{
  gim::binbag::CBinBag bb;
  CParameterData replyData;
  replyData.EncodeTo(&bb);
  CParameterXML pxml;

  if(parameterdata.GetCommand()->cmd == KCommandGetParameters){
    dPrint(ODINFO,"Got command: Get Parameters...");
    parameterArray.clear();
    std::string s;
    std::stringstream out;
    out << brightnessValue;
    s = out.str();
    TParameterInfo info(std::string("Brightness"),
                        std::string("Changes brightness of image"),
                        s,
                        std::string("0-100"),
                        std::string(""));

    std::stringstream out2;
    out2 << contrastValue;
    s = out2.str();
    TParameterInfo info2(std::string("Contrast"),
                         std::string("Changes contrast of image"),
                         s,
                         std::string("0-300"),
                         std::string(""));
  
    parameterArray.push_back(info);
    parameterArray.push_back(info2);
    pxml.SetParameterInfoArray(parameterArray);
    bool r = pxml.EncodeParameterXML();
    if( r){
      std::string encodedString =  pxml.GetXMLData();
      replyData.SetCommand(TCommand(KCommandGetParametersReply));
      replyData.SetParameterXMLString(encodedString);
      dPrint(ODINFO,"Sending reply.");
      ps->SendReply(replyData,ms);
    }else{
      dPrint(1,"Failed to encode to XML format.");
    }

  }else if(parameterdata.GetCommand()->cmd == KCommandSetParameter){
    const TParameterXML *pxmlstring =parameterdata.GetParameterXML();
    pxml.DecodeParameterXML(std::string(pxmlstring->GetTextPtr()));
    TParam parameter;
    if(pxml.GetParameter(parameter)){
      if(parameter.key.compare("Brightness") == 0){
        int newBrightness =-1;
        sscanf(parameter.value.c_str(),"%d", &newBrightness);
        if(newBrightness >= 0 && newBrightness <= 100){
          dPrint(1,"Setting 'Brightness' to %d", newBrightness);
          brightnessValue = newBrightness;
        }else{
          dPrint(1,"Brightness value out of range");
        }
        
      }else if(parameter.key.compare("Contrast") == 0){
        int newContrast =-1;
        sscanf(parameter.value.c_str(),"%d", &newContrast);
        if(newContrast >= 0 && newContrast <= 300){
          dPrint(1,"Setting 'Contrast' to %d", newContrast);
          contrastValue = newContrast;
        }else{
          dPrint(1,"Contrast value out of range");
        }
      
      }else{
        dPrint(ODERROR,"Didn't recognize key '%s'. Ignoring",parameter.key.c_str());
      }


    }else{
      dPrint(ODERROR,"Failed to get parameter information from parameter data");
    }
  }
}
//*****************************************************************************

static int dummyWatch(CParameterServer *ps)
{
  CParameterData pd;
  SMessageSource ms;

  EMaCIError e;

  while(run) {
    e = ps->WaitCommand(pd, ms, 1000);
    if (e == KMaCIOK) {
      const TCommand *c = pd.GetCommand();
      if (c) {
        dPrint(2,"Got command: %d", c->cmd);
        switch(c->cmd) {
        case KCommandGetParameters:
        case KCommandSetParameter:

          DummyExecuteParameterQuery(ps, pd, ms, c);
          break;
        
        default:
          dPrint(ODINFO,"Unidentified command for parameter dummy '%d'",c->cmd);
          break;
        
        
          
        }
      } else {
        dPrint(ODERROR,"Got Command, but no Command element present???");

      }
    }
  }
  
  return 0;
}
//*****************************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  // Construct an MaCICtrlServer instance
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);

  // Construct instance of ParameterServer
  CParameterServer ps(&mcs, 0, "Parameter dummy service", "PArams");

  // Construct instance of ParameterData && Init to use internal BinBag
  CParameterData pd;
  pd.CreateInternalBinBag();


  // Set GroupName for MaCICtrlServer and Instance for ParameterServer.
  mcs.SetGroupName(macigroup);
  ps.SetInterfaceInstanceName("Dummy");

  // Init random number generator
  // srandom(time(NULL));
  
  // Enable the Reporting interface.
  //  ds.EnableAlarmServer();
  //assert(ds.GetAlarmServerPtr() != NULL);


  // Create command watch.
  ownThreadHandle dummyWatchThread;

  if (ps.Open() == KMaCIOK) {
    // Run!
    dummyWatchThread = ownThread_Create((void*)dummyWatch, &ps);

    // At this point, we have a preconnected GIMI, so now its up to you
    // to do things.  For more examples of functionality and structure,
    // see other MaCI modules, such as Alarm_SQL.cpp.
    while(run) {
      
      ownSleep_ms(1000);
    }

    // Add a call to gimi:stop()
    g.stop();

    // wait until the command handling thread terminates.
    ownThread_Join(dummyWatchThread, NULL);

  } else {
    dPrint(ODERROR,"Failed to open CParameterServer instance! Fatal error.");
    return -1;

  }
  

  return 0;
}
//*****************************************************************************

//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(verbose);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.2 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'f':
      configurationFile = optarg;
      dPrint(ODVINFO,"Using configuration file: '%s'", optarg);
     
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(ODVINFO,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(ODVINFO,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(ODVINFO,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(ODVINFO,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}

